package com.lsh.unit;

import com.lsh.entity.FastDFSModel;
import org.apache.commons.io.FileUtils;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/9/17 8:29 下午
 * @desc ：实现文件管理
 *          文件上传
 *          文件下载
 *          文件删除
 *          文件信息获取
 *          Storage信息获取
 *          Tracker信息获取
 *
 *
 */
public class FastDFSUtil2 {
    //加载Tracker连接信息
    static {
        try {
            //String fdfsconfpath = "/Users/LiuShihao/IdeaProjects/mychanggou/mychanggou-service/mycahnggou-service-file/src/main/resources/fdfs_client.conf";
            //查找classpath下的文件的路径
//            String path = new ClassPathResource("fdfs_client.conf").getPath();
            ClassPathResource classPathResource = new ClassPathResource("fastdfs-client.properties");
            InputStream inputStream = classPathResource.getInputStream();
            File fastdfsfile = new File("/data/FastDFS/fastdfs-client.properties");
            FileUtils.copyInputStreamToFile(inputStream,fastdfsfile);
            ClientGlobal.init("/data/FastDFS/fastdfs-client.properties");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     * @param fastDFSFile   上传的文件信息封装
     */
    public static String[] upload(FastDFSModel fastDFSFile) throws Exception {

        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        /**
         * 通过StorageClient访问Storage,实现文件上传，并获取文件上传后的存储信息
         * 1.上传文件的字节数组
         * 2. 上传文件的扩展名
         * 3. 上传文件的附加信息
         */
        //附加信息：  创建文件附加信息   可以用于文件上传的第三个参数   比如  Author：lsh   拍摄地址：上海   拍摄终端：iPhone 11 Pro Max
//        NameValuePair[] meta_list = new NameValuePair[1];
//        meta_list[0] = new NameValuePair("name",fastDFSFile.getAuthor());
        String[] upload = storageClient.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), null);
        /**
         * upload_file返回参数：upload[]
         * 1. upload[0]：文件上传所存储的组名                  group1
         * 2. upload[1]：文件存储到Storage上的文件名字          M00/02/14/wyt.jpg
         * 也可以获得StorageClient1客户端 直接使用upload_file1 方法
         */
        return upload;
    }

    /**
     * 获取文件信息
     * @param groupName          group1
     * @param remoteFileName  M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg
     * @return
     * @throws Exception
     */
    public static FileInfo getFileInfo(String groupName, String remoteFileName) throws Exception {
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        return storageClient.get_file_info(groupName,remoteFileName);

    }

    /**
     * 下载文件
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws Exception
     */
    public static InputStream downloadFile(String groupName, String remoteFileName)throws Exception{
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        //文件下载
        byte[] bytes = storageClient.download_file(groupName, remoteFileName);

        return new ByteArrayInputStream(bytes);

    }

    /**
     * 删除文件
     * @param groupName
     * @param remoteFileName
     * @throws Exception
     */
    public static void deleteFile(String groupName, String remoteFileName)throws Exception{
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);

        //文件删除
        storageClient.delete_file(groupName,remoteFileName);

    }

    public static String getTrackerInfo()throws Exception{
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = getStorageClient(trackerServer);
        //获取Tracker的端口
        String hostString = trackerServer.getInetSocketAddress().getHostString();
        int tracker_http_port = ClientGlobal.getG_tracker_http_port();
        String url = "http://"+hostString+":"+tracker_http_port;
        return  url;

    }

    /**
     * 获取TeackerServer
     * @return
     * @throws IOException
     */
    public static TrackerServer getTrackerServer() throws IOException {
        //创建一个Tracker访问的客户端对象TrackerClient
        TrackerClient trackerClient = new TrackerClient();

        //通过TrackerClient访问TrackerServer服务，获取连接信息
        TrackerServer trackerServer = trackerClient.getConnection();

        return trackerServer;

    }

    /**
     * 获取StorageClient
     * @param trackerServer
     * @return
     */
    public static StorageClient getStorageClient(TrackerServer trackerServer){
        //通过TrackerServer的连接信息可以获取Storage的连接信息，创建StorageClient对象存储storage连接信息
        StorageClient storageClient = new StorageClient(trackerServer, null);

        return storageClient;
    }








    public static void main(String[] args) throws Exception {
        //获取文件信息
//        FileInfo file = getFileInfo("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
//        System.out.println("FileSize:"+file.getFileSize());
//        System.out.println("IPAddr:"+file.getSourceIpAddr());


//        //文件下载
//        InputStream is = downloadFile("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
//        FileOutputStream os = new FileOutputStream("/Users/LiuShihao/Desktop/1.jpeg");
//        //定义一个缓冲区
//        byte[] buffer = new byte[1024];
//        while(is.read(buffer)!=-1){
//            os.write(buffer);
//        }
//        os.flush();
//        os.close();
//        is.close();

        //文件删除
//        deleteFile("group1", "M00/00/00/rB52RF9jaiSAP9oLAAFDcbOOQqw66.jpeg");
//      获取Tracker信息  IP+Port
//        System.out.println(getTrackerInfo());

    }
}
